<?php

/*
supplier_goods_model.php : 处理供应商和货品之间的关系
*/

class Suppliers_Goods_model extends CI_Model
{

	private $table = 'suppliers_goods';
	public $error = '';

	public function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');
		$this->test_database->test();
		//载入核心类
		$this->load->database($this->test_database->get_db());
	}

	//获得当前子货品存在的供应商，并返回供应商id[object]
	public function get_suppliers($sub_goods_id, $detail=false)
	{
		$this->load->model('Supplier_model');
		$this->db->where('sub_goods_id', $sub_goods_id);
		$query = $this->db->get($this->table);
		$suppliers = $query->result();
		if ($detail)
		{
			foreach ($suppliers as $k=>$s)
			{
				$supplier = $this->Supplier_model->getOne($s->supplier_id);
				if (1 == $supplier['del_flg'])
				{
					unset($suppliers[$k]);
				}
				else
				{
					$suppliers[$k]->detail = $supplier;
				}
			}
		}
		return $suppliers;
	}

	public function update($sub_goods_id)
	{
		$data = array();
		$supplier_ids = $this->supplier_ids_to_array($this->input->post('supplier_ids'));
		//过滤已存在的子货品和供应商关系
		$this->db->where('sub_goods_id', $sub_goods_id);
		$query = $this->db->get($this->table);
		foreach ($query->result() as $key => $q)
		{
			if (in_array($q->supplier_id, $supplier_ids))
			{
				unset($supplier_ids[$key]);
			}
		}
		//如果全部被过滤，不进行更新操作
		if (count($supplier_ids) == 0) return false;
		//处理数据准备插入
		foreach ($supplier_ids as $supplier_id)
		{
			$data[] = array(
				'supplier_id'	=> $supplier_id,
				'sub_goods_id'	=> $sub_goods_id,
				'goods_prices'	=> '',
				'create_update'	=> time(),
				'del_flg'		=> 0
				);
		}
		$this->db->insert_batch($this->table, $data);
		return true;
	}

	public function get_one_by_ss($sub_goods_id, $supplier_id)
	{
		$this->db->where('sub_goods_id', $sub_goods_id);
		$this->db->where('supplier_id', $supplier_id);
		$query = $this->db->get($this->table);
		if ($query->num_rows() == 1)
		{
			return true;
		}
		$this->error = '不存在对应关系';
		return false;
	}

	public function supplier_ids_to_array($supplier_ids)
	{
		return explode('|', $supplier_ids);
	}

}